<script setup lang="ts">
import { addCategory, deleteCategorys, getCategory, getCategoryDetail, upCategory } from "@/api/marketers/category";
import { handleTree } from "@/utils/ruoyi";
import { ElMessage, type FormInstance } from "element-plus";
import { reactive, ref, toRef, toRefs } from "vue";
interface Category {
  categoryId: number;
  parentId: number;
  name: string;
  isDeleted: number;
  level: number;
  path: string;
  sortOrder: number;
  status: number;
  updateTime: string;
  createTime: string;
  hasChildren?: boolean;
  children: Category[];
}
const formEl =ref()
const title = ref();
const dialogVisible = ref(false);
const isSumbit = ref(true);
const loading =ref(false)
const tableList = ref<Category[]>([]);
//表单校验
const nameValidator = (rule: any, value: any, callback: any) => {

if (!value || value.trim() === '') {
              callback(new Error('名称不能为空'));
} else if (value.trim().length < 1 || value.trim().length > 10) {
  callback(new Error('长度为1到10位'))
} else {
  callback()
}
}
const data = reactive({
  form: <Category>{
    parentId:0,
    status:1
  },
  rules: {    name: [
        {
            required: true,
            validator: nameValidator,
            trigger: 'blur',
        },
    ],},
});
const { form, rules } = toRefs(data);

const categoryList=ref()
//获取商品分类列表
async function getCategoryList(){
  loading.value=true
  await getCategory({}).then((response) => {
  tableList.value = handleTree(response.data.data, "categoryId", "parentId", "children");
});
loading.value=false
}



// 修改按钮
const handleUpdate = (item: any) => {
  title.value = "修改";
  dialogVisible.value = true;
  isSumbit.value = false;
  //获取商品分类详细
  getCategoryDetail(item.categoryId).then((data) => {
    form.value = data.data.data;
  });

};
//新增按钮
const handleAdd = (item: any) => {
  title.value = "新增";
  isSumbit.value = true;
  dialogVisible.value = true;
  if (item.categoryId !== null && item.categoryId !== undefined) {
    getCategoryDetail(item.categoryId).then((response) => {
        form.value.parentId = response.data.data.categoryId
    })

  }
};
// 删除按扭
const handleDelete = async (item: Category) => {
  console.log(item)
  if (item.children !== undefined) {
    ElMessage({
      message: "存在子菜单，不可删除.",
      type: "warning",
    });
  }
    else {
        await deleteCategorys([item.categoryId]).then((response) => {
    ElMessage.success(response.data.msg);
  });
    }
    getCategoryList()
};

//提交按钮
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            if (isSumbit.value) {
                await addCategory(form.value).then((response) => {
    ElMessage.success(response.data.msg);
  });
            } else {
                await upCategory(form.value).then((response) => {
    ElMessage.success(response.data.msg);
  });
            }
            dialogVisible.value = false
            getCategoryList()
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
getCategoryList()
</script>
<template>
  <el-button type="primary" @click="handleAdd">新增</el-button>
  <el-divider />
  <el-table
    :data="tableList"
    v-loading="loading"
    row-key="categoryId"
    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    style="width: 100%; height: 70vh"
  >
    <el-table-column prop="name" label="名称" :show-overflow-tooltip="true" />
    <!-- <el-table-column prop="path" label="路径" :show-overflow-tooltip="true" /> -->
    <el-table-column prop="status" label="状态" :show-overflow-tooltip="true">
      <template #default="scope">
        <el-tag :value="scope.row.status">{{
          scope.row.status ? "启用" : "停用"
        }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" :show-overflow-tooltip="true" />
    <el-table-column
      label="操作"
      align="center"
      width="210"
      class-name="small-padding fixed-width"
    >
      <template #default="scope">
        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
          >修改</el-button
        >
        <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
          >新增</el-button
        >
        <el-popconfirm title="确定要删除吗？" @confirm="handleDelete(scope.row)">
          <template #reference>
            <el-button link type="primary" icon="Delete">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <!-- 新增修改 -->
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="800"
    @close="resetForm(formEl)"
  >
    <el-form
      :model="form"
      ref="formEl"
      :rules="rules"
      style="max-width: 600px"
      label-width="auto"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item prop="parentId" label="上级分类">
            <el-tree-select
              v-model="form.parentId"
              :props="{ label: 'name', value: 'categoryId' }"
              :data="tableList"
              check-strictly
              :render-after-expand="false"
            >
            </el-tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="name" label="分类名称">
            <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="status" label="状态">
            <el-radio-group v-model="form.status">
              <el-radio :value="1">启用</el-radio>
              <el-radio :value="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-button @click="submitForm(formEl)">确定</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
